package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author liuyp
 * @date 2021/02/04
 */
@Service
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addFriend(long userId1, long userId2) {
        //如果userId1没有好友userId2
        Criteria criteria = Criteria.where("userId").is(userId1).and("friendId").is(userId2);
        Query query = new Query(criteria);
        if (!mongoTemplate.exists(query, Friend.class)) {
            //给userId1添加了好友：userId2
            Friend friend = new Friend();
            friend.setId(ObjectId.get());
            friend.setUserId(userId1);
            friend.setFriendId(userId2);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        //如果userId2没有好友userId1
        criteria = Criteria.where("userId").is(userId2).and("friendId").is(userId1);
        if (!mongoTemplate.exists(new Query(criteria), Friend.class)) {
            //给userId2添加好友 ：userId1
            Friend friend = new Friend();
            friend.setId(ObjectId.get());
            friend.setUserId(userId2);
            friend.setFriendId(userId1);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

    }

    @Override
    public PageResult<Friend> findFriendList(long userId, String keyword, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1, pagesize));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int)count, pagesize, pages, page, friendList);
    }
}

